using System;
using System.Collections.Generic;
using UnityEngine;

namespace M13.Game.Entity.FSM
{
    public class StateMachine : MonoBehaviour
    {
        public IState lastState;
        public IState currentState;
        protected Dictionary<System.Type, IState> stateTable;

        public bool SwitchState(Type newStateType)
        {
            IState newState = stateTable[newStateType];
            if (newState == null) return false;

            if (currentState != null)
            {
                if (currentState.TryExit() && newState.TryEnter())
                {
                    lastState = currentState;
                    currentState.Exit();
                    currentState = newState;
                    currentState.Enter();
                    Debug.Log($"状态：{currentState.GetStateName()}");
                    return true;
                }
                lastState = currentState;
                return false;
            }
            lastState = currentState;
            currentState = newState;
            currentState.Enter();
            Debug.Log($"状态：{currentState.GetStateName()}");
            return true;
        }


        public void SwitchOnSeveralState(params Type[] states)
        {
            for(int i = 0; i < states.Length; i++)
            {
                if (SwitchState(states[i]))
                {
                    return;
                }
            }
        }

        public bool IsLastState(Type lastState)
        {
            return lastState == this.lastState.GetType();
        }
    }
}